package com.yonyou.demo;

import com.intellij.notification.NotificationType;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
import com.yonyou.biz.vo.GitLogContext;
import com.yonyou.biz.vo.MyPluginState;
import com.yonyou.common.git.GiLogMRProcess;
import com.yonyou.common.git.GiLogQueryProcess;
import com.yonyou.utils.GitUtils;
import com.yonyou.utils.MyPluginStateComponent;
import git4idea.GitLocalBranch;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.gitlab4j.api.*;
import org.gitlab4j.api.models.*;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;



import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;

@SuppressWarnings("serial")
public class UserListPanel extends JPanel implements ActionListener {

	private JTable table;
	private MyTableModel model;
	private List<Commit> list = new ArrayList<>();


	private JTextField keyField;
	private JTextField git_token;
	private JTextField shenpiren;
	private JComboBox<String> roleListBox;
	private JTextField git_branch;

	private PagePanel p;

	private UserSearch search = new UserSearch();
	private GitLogContext context;
	public UserListPanel(GitLogContext context) {
		this.context=context;
		try {
			setLayout(new BorderLayout(0, 0));
			setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
			JPanel panel = new JPanel();
			add(panel, BorderLayout.NORTH);

			JLabel label1 = new JLabel("GIT秘钥：");
			panel.add(label1);
			git_token = new JTextField(20);

			MyPluginState state = MyPluginStateComponent.getInstance().getState();
			git_token.setText(state.getGit_token());
			panel.add(git_token);

			JButton editBtn = new JButton("修改秘钥");
			editBtn.addActionListener(this);
			editBtn.setActionCommand("editToken");
			panel.add(editBtn);

			JLabel label2 = new JLabel("审批人（ID）：");
			panel.add(label2);

			shenpiren = new JTextField(15);
			shenpiren.setText(state.getShenpi_id());
			shenpiren.addFocusListener(new FocusAdapter() {
				@Override
				public void focusLost(FocusEvent e) {
					// 当 JTextField 失去焦点时，这个方法会被调用
					// 然后进行验证或其他处理
					String text =shenpiren.getText();
					if(StringUtils.isNotEmpty(text)){
						if (!text.matches("\\d*")) { // 如果输入不匹配数字模式
							// 处理错误，例如显示错误消息或清除输入
							JOptionPane.showMessageDialog(panel, "审批人为数字ID！");
							// 可选：清除输入
							shenpiren.setText("");
						}

						state.setShenpi_id(text);
					}
				}
			});


			panel.add(shenpiren);

			JLabel label3 = new JLabel("目标分支：");
			panel.add(label3);

			final List<String> collect = GitUtils.getCurrentBranchList(this.context.getProject());
			String[] array = collect.toArray(new String[0]);
			roleListBox = new JComboBox<>(array);
			roleListBox.setSize(new Dimension(800, 100));
			roleListBox.addItemListener(new ItemListener() {
				@Override
				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() == ItemEvent.SELECTED) {
						// 当选项被选中时执行的操作
						String selectedItem = (String)e.getItem();
						List<String> branch_list=new ArrayList<>();
						List<String> branch_lists =StringUtils.isEmpty(git_branch.getText())?new ArrayList():Arrays.asList(git_branch.getText().split(","));
						branch_list.addAll(branch_lists);
						if(!branch_lists.contains(selectedItem)){
							branch_list.add(selectedItem);
						}
						git_branch.setText(String.join(",", branch_list));
					}
				}
			});

			panel.add(roleListBox);
			git_branch = new JTextField(30);
			panel.add(git_branch);


			JLabel label = new JLabel("关键字：");
			panel.add(label);

			UserListPanel userListPanel = this;
			keyField = new JTextField(20);
			keyField.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						try {
							final GitRepository currentRepository = GitBranchUtil.getCurrentRepository(context.getProject());
							search.setKey(keyField.getText());
							if(checkGit(userListPanel,currentRepository,false)){
								ProgressManager.getInstance().run(
										new GiLogQueryProcess(userListPanel.context,userListPanel,currentRepository));
							}
							//model.fireTableDataChanged();
						} catch (Exception ex) {
							throw new RuntimeException(ex);
						}
					}
				}
			});
			panel.add(keyField);

			JButton btnNewButton = new JButton("搜索");
			btnNewButton.addActionListener(this);
			btnNewButton.setActionCommand("search");
			panel.add(btnNewButton);


			JButton btnNewButton_1 = new JButton("合并");
			btnNewButton_1.addActionListener(this);
			btnNewButton_1.setActionCommand("add");
			panel.add(btnNewButton_1);

			model = new MyTableModel();

			// 创建一个表格，指定 表头 和 所有行数据
			table = new JTable(model);

			table.setRowHeight(28);
			table.getTableHeader().setPreferredSize(new Dimension(0, 30));
			table.getColumnModel().getColumn(0).setMinWidth(150);
			table.getColumnModel().getColumn(1).setMinWidth(70);
			table.getColumnModel().getColumn(2).setMinWidth(100);
			table.getColumnModel().getColumn(3).setMinWidth(250);
			table.getColumnModel().getColumn(4).setMinWidth(300);

			MyTableCellRenderer renderer = new MyTableCellRenderer();
			// 遍历表格的每一列，分别给每一列设置单元格渲染器
			for (int i = 0; i < table.getColumnCount(); i++) {
				// 根据 列名 获取 表格列
				TableColumn tableColumn = table.getColumnModel().getColumn(i);
				// 设置 表格列 的 单元格渲染器
				tableColumn.setCellRenderer(renderer);
				tableColumn.sizeWidthToFit();

			}

			// 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
			table.setPreferredScrollableViewportSize(new Dimension(400, 300));

			JScrollPane scrollPane = new JScrollPane(table);

			add(scrollPane, BorderLayout.CENTER);

			p = new PagePanel();
			add(p, BorderLayout.SOUTH);

			p.setListener((index, len) -> {

				try {
					//ProgressManager.getInstance().run(
					//		new GiLogQueryProcess(this.context,userListPanel));
					search.setIndex(index);
					search.setLen(len);
					//model.fireTableDataChanged();

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			});
			p.setCountListener(()->{
				return list.size();
			});
			p.setRowMax(10);
			p.setPage(1);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	org.gitlab4j.api.models.Project gitProject;
	CommitsApi commitsApi;
	MergeRequestApi mergeRequestApi;

	@Override
	public void actionPerformed(ActionEvent e) {
		UserListPanel userListPanel = this;
		final GitRepository currentRepository = GitBranchUtil.getCurrentRepository(this.context.getProject());
		switch (e.getActionCommand()) {

		case "search":// 搜索
			if(checkGit(userListPanel,currentRepository,false)){
				ProgressManager.getInstance().run(
						new GiLogQueryProcess(this.context,userListPanel,currentRepository));
			}
			break;
		case "add":
			List<String> branch_lists =StringUtils.isEmpty(git_branch.getText())?new ArrayList():Arrays.asList(git_branch.getText().split(","));
				final String name = currentRepository.getCurrentBranch().getName();
				if(name.toLowerCase().contains("features")||name.toLowerCase().contains("bugfix")){
					if(CollectionUtils.isEmpty(branch_lists)){
						com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showErrDialog("操作异常","请选择合并目标分支！");
						return ;
					}

					if(checkGit(userListPanel,currentRepository,true)){
						int result = Messages.showYesNoDialog(
								this.context.getProject(),
								"点击确认按钮后，"+"代码异步合并至："+git_branch.getText()+"分支，确认后、请勿其他操作、稍后消息栏查看结果！是否继续？",
								"确认",
								Messages.getQuestionIcon()
						);
						if (result == Messages.YES) {
							for(String br : branch_lists){
								GiLogMRProcess giLogMRProcess = new GiLogMRProcess(this.context, br, userListPanel,currentRepository);
								ProgressManager.getInstance().run(giLogMRProcess);
							}
							StatusBar statusBar = WindowManager.getInstance().getStatusBar(this.context.getProject());
							JBPopupFactory.getInstance()
									.createHtmlTextBalloonBuilder("合并代码至："+git_branch.getText(), MessageType.INFO, null)
									.setFadeoutTime(3500)
									.createBalloon()
									.show(RelativePoint.getCenterOf(statusBar.getComponent()), Balloon.Position.above);

						}
					}
				}else{
					com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showErrDialog("操作异常","当前分支名错误、必须包含【features、bugifx】！");
				}
				break;
		case "editToken":
			//int index = table.getSelectionModel().getMinSelectionIndex();
			//if(index==-1){
			//	JOptionPane.showMessageDialog(null, "请选择要修改的数据");
			//	break;
			//}
			//p.reload();
			final String text = git_token.getText();
			if(StringUtils.isEmpty(text)){
				com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.ERROR,"git秘钥不可为空！，请重试！！");
			}
			MyPluginState state = MyPluginStateComponent.getInstance().getState();
			state.setGit_token(text);
			com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showNotification(NotificationType.INFORMATION,"git秘钥本地保存成功！！");
			break;
		case "delete":
			int[] indexs=table.getSelectedRows();
			if(indexs.length==0){
				JOptionPane.showMessageDialog(null, "请选择要删除的数据");
			}else{
				int btnType=JOptionPane.showConfirmDialog(null, "您确定要删除选择的["+indexs.length+"]条数据吗?");
				if(btnType==JOptionPane.OK_OPTION){

					p.reload();
				}
			}
			break;
		default:
			break;
		}

	}

	private boolean checkGit(UserListPanel userListPanel, GitRepository currentRepository ,boolean ischeck) {
		int itemCount = roleListBox.getItemCount();
		if (itemCount <= 0) {
			final List<String> collect =  GitUtils.getCurrentBranchList(this.context.getProject());
			String[] array = collect.toArray(new String[0]);
			for(String a :array){
				roleListBox.addItem(a);
			}
		}
		try {
			if(StringUtils.isEmpty(this.git_token.getText())){
				com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showErrDialog("操作异常","git秘钥不可为空！，请先填写后查询！！");
				return false;
			}

			return true;
		} catch (Exception ex) {
			com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showErrDialog("操作异常",ex.getMessage());
			return false;
		}
	}

	public class MyTableModel extends AbstractTableModel {

		private String[] columes = { "ID", "提交人", "提交时间", "提交标题", "提交内容"};

		@Override
		public String getColumnName(int column) {
			return columes[column];
		}

		@Override
		public int getRowCount() {
			return list.size();
		}

		@Override
		public int getColumnCount() {
			return columes.length;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			switch (columnIndex) {
			case 0:
				return list.get(rowIndex).getId();
			case 1:
				return list.get(rowIndex).getCommitterName();
			case 2:
				return  new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(list.get(rowIndex).getCommittedDate());
			case 3:
				return list.get(rowIndex).getTitle();
			case 4:
				return list.get(rowIndex).getMessage();
			default:
				return null;
			}
		}

	}



	private class MyTableCellRenderer extends DefaultTableCellRenderer {

		@Override
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
				int row, int column) {



			setHorizontalAlignment(SwingConstants.CENTER);

			//if (row % 2 == 0) {
			//	setBackground(Color.WHITE);
			//} else {
			//	setBackground(new Color(230, 230, 230));
			//}

			return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
		}
	}


	public JTable getTable() {
		return table;
	}

	public void setTable(JTable table) {
		this.table = table;
	}

	public MyTableModel getModel() {
		return model;
	}

	public void setModel(MyTableModel model) {
		this.model = model;
	}

	public List<Commit> getList() {
		return list;
	}

	public void setList(List<Commit> list) {
		this.list = list;
	}

	public JTextField getKeyField() {
		return keyField;
	}

	public void setKeyField(JTextField keyField) {
		this.keyField = keyField;
	}

	public JTextField getGit_token() {
		return git_token;
	}

	public void setGit_token(JTextField git_token) {
		this.git_token = git_token;
	}

	public JComboBox<String> getRoleListBox() {
		return roleListBox;
	}

	public void setRoleListBox(JComboBox<String> roleListBox) {
		this.roleListBox = roleListBox;
	}

	public PagePanel getP() {
		return p;
	}

	public void setP(PagePanel p) {
		this.p = p;
	}

	public UserSearch getSearch() {
		return search;
	}

	public void setSearch(UserSearch search) {
		this.search = search;
	}

	public GitLogContext getContext() {
		return context;
	}

	public void setContext(GitLogContext context) {
		this.context = context;
	}

	public Project getGitProject(GitLabApi gitLabApi, GitRepository repository) throws Exception {
		List<org.gitlab4j.api.models.Project> projects  = gitLabApi.getProjectApi().getProjects();
		Project  gitProject =projects.stream().filter(p->p.getName().equals(repository.getProject().getName())).findFirst().get();

		return gitProject;
	}

	public void setGitProject(Project gitProject) {
		this.gitProject = gitProject;
	}

	public CommitsApi getCommitsApi() {
		return commitsApi;
	}

	public void setCommitsApi(CommitsApi commitsApi) {
		this.commitsApi = commitsApi;
	}

	public MergeRequestApi getMergeRequestApi() {
		return mergeRequestApi;
	}

	public void setMergeRequestApi(MergeRequestApi mergeRequestApi) {
		this.mergeRequestApi = mergeRequestApi;
	}

	public JTextField getGit_branch() {
		return git_branch;
	}

	public void setGit_branch(JTextField git_branch) {
		this.git_branch = git_branch;
	}

	public JTextField getShenpiren() {
		return shenpiren;
	}

	public void setShenpiren(JTextField shenpiren) {
		this.shenpiren = shenpiren;
	}
}
